package com.hjm.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String HH_MM_SS = "HH:mm:ss";

    /** yyyyMMddHHmmssSSS */
    private static final DateTimeFormatter YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_S = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    /** yyyy-MM-dd HH:mm:ss */
    private static final DateTimeFormatter YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_EN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 时间戳转字符串日期/时间
     * @param seconds 时间戳（毫秒）
     * @param pattern 时间格式
     * @return 格式化的日期/时间
     */
    public static String timeStampToDate(Long seconds, String pattern) {
        String time = "";
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds / 1000L, 0, ZoneOffset.ofHours(8));
        if (seconds != 0){
            time = dateTime.format(DateTimeFormatter.ofPattern(pattern));
        }
        return time;
    }


    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }
    public static String getDateYyyyMMdd()
    {
        return dateTimeNow(YYYYMMDD);
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM
     *
     * @return String
     */
    public static String getDateYYYY_MM()
    {
        return dateTimeNow(YYYY_MM);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String getOnlyTime()
    {
        return dateTimeNow(HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }


    /**
     *
     *********************************************************.<br>
     * [方法] daysBetween <br>
     * [描述] (比较两个时间相差多少天 单位是天数) <br>
     * [参数] (smdate 起始日期  edate 结束日期 ) <br>
     * [返回] int <br>
     *********************************************************.<br>
     */
    public static Integer daysBetween(String sdate, String edate) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);

            Calendar cal = Calendar.getInstance();

            cal.setTime(sdf.parse(sdate));
            long time1 = cal.getTimeInMillis();

            cal.setTime(sdf.parse(edate));

            long time2 = cal.getTimeInMillis();

            long between_days = (time2 - time1) / (1000 * 3600 * 24);

            return Integer.parseInt(String.valueOf(between_days));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前日期(yyyyMMddHHmmssSSS)
     * @return String
     */
    public static String getSimpleDateTimeMillisecond() {
        return LocalDateTime.now().format(YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_S);
    }

    /**
     * 获取当前时间（yyyy-MM-dd HH:mm:ss）
     * @return String
     */
    public static String getDateTime() {
        return LocalDateTime.now().format(YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_EN);
    }



    /**
     * ********************************
     * 方法:getDate
     * 参数:{num 获取当前日期的前后天数 (年)}
     * 作者:Gd
     * 返回:String
     * ********************************
     */
    public static String getYear(String format,int num){
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, num);
        date = calendar.getTime();
        return sdf.format(date);
    }


    /**
     * ********************************
     * 方法:getDate
     * 参数:{num 获取当前日期的前后天数 (天)}
     * date 字符串时间
     * num 加减天数
     * format 格式 如  yyyy-MM-dd
     * 作者:Gd
     * 返回:String
     * ********************************
     */
    public static String getDay(String format,int num,String dates) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        Date date = sdf.parse(dates);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, num);
        date = calendar.getTime();
        return sdf.format(date);
    }

    /**
     * ********************************
     * 方法:getDate
     * 参数:{num 获取当前日期的前后天数 (天)}
     * Date 字符串时间
     * num 加减天数
     * format 格式 如  yyyy-MM-dd
     * 作者:Gd
     * 返回:String
     * ********************************
     */
    public static String getDateDay(String format,int num,Date date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, num);
        date = calendar.getTime();
        return sdf.format(date);
    }


    /**
     * 根据当前时间往前 或 往后 +1个月
     * @Param [format, num, date]
     * @Return java.lang.String
     */
    public static String getDateMonth(String format,int num) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, num);
        date = calendar.getTime();
        return sdf.format(date);
    }




    /**
     * 比对两个日期大小
     * @Param [format 要格式化的日期格式, date 第一个日期, date1 第二个日期]
     * @Return boolean
     */
    public static boolean compareDate(String format,String date,String date1) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        Date parse = sdf.parse(date);
        Date parse1 = sdf.parse(date1);
        if (parse.before(parse1)) {
            return true;
        }
          return false;
    }


    /**
     * 获取当前时间所在周的周一和周日的日期时间
     * @return
     */
    public static Map<String,String> getWeekDate() {
        Map<String,String> map = new HashMap();
        map.size();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);

        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String weekEnd = sdf.format(sundayDate);

        map.put("startDate", weekBegin);
        map.put("endDate", weekEnd);
        return map;
    }


    /**
     * 将时间戳转换为时间
     * @return
     */
    public static Date stampToTime(String longTime) throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(longTime);
        //将时间戳转换为时间
        Date date = new Date(lt);
        return date;
    }

    public static void main(String[] args) throws Exception {
        //boolean b = compareDate("yyy-MM-dd", "2021-03-01", "2021-03-02");

        //String day = DateUtils.getDateMonth(DateUtils.YYYY_MM_DD, 1);
        Date date = DateUtils.stampToTime("1666278188000");
        System.out.println(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
        String format = simpleDateFormat.format(date);



        System.out.println(format);

        //System.out.println(b);
    }
}
